<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { TransactionOrderApi } from '@/api/TransactionOrderApi.js';
import { MarketItemApi } from '@/api/new/MarketItemApi.ts';
import UserUtil from '@/utils/User/User.js';
import { ChatSessionApi } from '@/api/ChatSessionApi.js';
import apiClient from '@/api/axios.js';
import { SecondHandItemApi } from '@/api/SecondHandItemApi.js';
import {UserProfileApi} from "@/api/new/userProfleApi";

const router = useRouter();
const loading = ref(true);
const orders = ref([]);
const activeTab = ref('all');
const reviewDialogVisible = ref(false);
const currentOrderId = ref(null);
const reviewForm = ref({
  rating: 5,
  comment: ''
});

// 默认图片
const defaultImage = 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png';

// 根据选项卡筛选订单
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value;
  }
  return orders.value.filter(order => order.status === activeTab.value);
});

// 切换标签页
const handleTabChange = () => {
  console.log('当前标签页:', activeTab.value);
};

// 获取用户订单
const fetchOrders = async () => {
  loading.value = true;
  try {
    const userInfo = await UserUtil.getUserInfo();
    if (!userInfo || !userInfo.userID) {
      ElMessage.warning('未登录或获取用户信息失败');
      return;
    }

    // 获取订单列表
    const response = await apiClient.get(`/transactionorder/buyer/${userInfo.userID}`);
    console.log('原始订单数据:', response.data);

    if (response && response.data) {
      // 处理订单数据
      orders.value = Array.isArray(response.data) ? response.data : [];
    } else {
      orders.value = [];
    }

    // 为每个订单获取商品信息
    orders.value = await Promise.all(orders.value.map(async (order) => {
      try {
        // 获取商品详情
        const itemResponse = await SecondHandItemApi.getSecondHandItemById(order.itemID);
        console.log(`商品 ${order.itemID} 响应:`, itemResponse);

        let itemData = {};
        if (itemResponse && itemResponse.data) {
          itemData = itemResponse.data;
        } else if (itemResponse && !itemResponse.data) {
          itemData = itemResponse;
        }

        // 获取商品图片
        let itemImage = defaultImage;
        try {
          const imageResponse = await MarketItemApi.getFirstItemImage(order.itemID);
          console.log(`商品 ${order.itemID} 图片响应:`, imageResponse);

          if (imageResponse) {
            if (typeof imageResponse === 'string') {
              try {
                const parsedImage = JSON.parse(imageResponse);
                itemImage = parsedImage.imageUrl || defaultImage;
              } catch (e) {
                itemImage = imageResponse || defaultImage;
              }
            } else if (imageResponse.imageUrl) {
              itemImage = imageResponse.imageUrl;
            }
          }
        } catch (error) {
          console.error(`获取商品 ${order.itemID} 图片失败:`, error);
        }

        // 获取卖家信息
        let sellerName = `用户${order.sellerID}`;
        try {
          const sellerResponse = await UserProfileApi.getUserInfo(order.sellerID);
          if (sellerResponse && sellerResponse.username) {
            sellerName = sellerResponse.username;
          }
        } catch (error) {
          console.error(`获取卖家 ${order.sellerID} 信息失败:`, error);
        }

        return {
          ...order,
          itemTitle: itemData.title || '未知商品',
          itemPrice: itemData.price || '0.00',
          itemImage,
          sellerName
        };
      } catch (error) {
        console.error(`处理订单 ${order.orderID} 失败:`, error);
        return {
          ...order,
          itemTitle: '未知商品',
          itemPrice: '0.00',
          itemImage: defaultImage,
          sellerName: `用户${order.sellerID}`
        };
      }
    }));

    orders.value.reverse()

    console.log('处理后的订单数据:', orders.value);
  } catch (error) {
    console.error('获取订单失败:', error);
    ElMessage.error(`获取订单失败: ${error.message}`);
    orders.value = [];
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';

  const time = new Date(timeStr);
  return `${time.getFullYear()}-${String(time.getMonth() + 1).padStart(2, '0')}-${String(time.getDate()).padStart(2, '0')} ${String(time.getHours()).padStart(2, '0')}:${String(time.getMinutes()).padStart(2, '0')}`;
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'inProgress':
    case 'inTransaction':
      return '交易中';
    case 'completed':
    case 'sold':
      return '已完成';
    case 'cancelled':
      return '已取消';
    default:
      return '未知状态';
  }
};

// 获取状态对应的标签类型
const getStatusType = (status) => {
  switch (status) {
    case 'inProgress':
    case 'inTransaction':
      return 'warning';
    case 'completed':
    case 'sold':
      return 'success';
    case 'cancelled':
      return 'info';
    default:
      return 'info';
  }
};

// 跳转到商品详情
const goToDetail = (itemId) => {
  router.push(`/secondhand/detail/${itemId}`);
};

// 查看订单详情
const viewOrderDetail = (orderID) => {
  router.push(`/secondhand/order/${orderID}`);
};

// 确认收货 - 更新商品状态为已售出(sold)
const confirmReceipt = async (orderID) => {
  try {
    await ElMessageBox.confirm('确认已收到商品并完成交易？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 查找当前订单，获取商品ID
    const currentOrder:any = orders.value.find(order => order.orderID === orderID);
    if (!currentOrder || !currentOrder.itemID) {
      ElMessage.error('找不到订单相关的商品信息');
      return;
    }
    console.log('订单',currentOrder);

    // 记录操作日志
    console.log(`确认收货: 订单ID=${orderID}, 商品ID=${currentOrder.itemID}`);

    // 使用修正后的方法更新商品状态为已售出(sold)
    const response = await SecondHandItemApi.updateItemStatus(currentOrder.itemID, 'sold');
    console.log('更新商品状态响应:', response);

    // 同时更新订单状态为已完成
    // 注意：这里需要使用订单系统的正确API
    const orderUpdateResponse = await apiClient.put('/transactionorder', {
      ...currentOrder,
      creationTime: new Date(currentOrder.creationTime).toUTCString(),
      status: 'completed'
    });
    console.log('更新订单状态响应:', orderUpdateResponse);

    ElMessage.success('交易已完成');
    // 刷新订单列表
    await fetchOrders();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error);
      ElMessage.error(`确认收货失败: ${error.message || '请稍后重试'}`);
    }
  }
};

// 取消订单 - 更新商品状态为在售(forSale)
const cancelOrder = async (orderID) => {
  try {
    await ElMessageBox.confirm('确定要取消此订单吗？', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 查找当前订单，获取商品ID
    const currentOrder = orders.value.find(order => order.orderID === orderID);
    if (!currentOrder || !currentOrder.itemID) {
      ElMessage.error('找不到订单相关的商品信息');
      return;
    }

    // 记录操作日志
    console.log(`取消订单: 订单ID=${orderID}, 商品ID=${currentOrder.itemID}`);

    // 使用修正后的方法更新商品状态为在售(forSale)
    const response = await SecondHandItemApi.updateItemStatus(currentOrder.itemID, 'forSale');
    console.log('更新商品状态响应:', response);

    // // 同时更新订单状态为已取消
    // // 注意：这里需要使用订单系统的正确API
    // const orderUpdateResponse = await apiClient.put('/transactionorder', {
    //   orderID: orderID,
    //   status: 'cancelled'
    // });
    // console.log('更新订单状态响应:', orderUpdateResponse);
    const orderUpdateResponse = await apiClient.put('/transactionorder', {
      ...currentOrder,
      creationTime: new Date(currentOrder.creationTime).toUTCString(),
      status: 'cancelled'
    });

    ElMessage.success('订单已取消');
    // 刷新订单列表
    await fetchOrders();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error);
      ElMessage.error(`取消订单失败: ${error.message || '请稍后重试'}`);
    }
  }
};

// 联系卖家
const contactSeller = async (sellerID, itemID) => {
  const userInfo = await UserUtil.getUserInfo();
  if (!userInfo || !userInfo.userID) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    // 创建聊天会话
    const response = await MarketItemApi.createChatSession(userInfo.userID, sellerID, itemID);
    const res = typeof response === 'string' ? JSON.parse(response) : response;

    if (res.status === 'error') {
      console.log('触发了聊天创建的error');
      console.log('尝试通过用户id获取聊天id');

      // 使用 ChatSessionApi 获取已存在的聊天会话
      try {
        const chatSession = await ChatSessionApi.getChatSessionByUserIds(userInfo.userID, sellerID);
        if (chatSession && chatSession.chatSessionID) {
          // 跳转到聊天页面
          router.push(`/chat?chatSessionID=${chatSession.chatSessionID}&otherUserID=${sellerID}`);
        } else {
          ElMessage.error('无法获取聊天会话');
        }
      } catch (error) {
        ElMessage.error(`获取聊天会话失败: ${error.message}`);
      }
    } else if (res.status === 'success' && res.chatSession) {
      console.log('聊天创建成功', res);
      // 跳转到聊天页面
      router.push(`/chat?chatSessionID=${res.chatSession.chatSessionID}&otherUserID=${sellerID}`);
    } else {
      ElMessage.error('创建聊天会话失败：返回数据格式不正确');
    }
  } catch (error) {
    ElMessage.error(`创建聊天失败: ${error.message}`);
  }
};

// 打开评价对话框
const openReviewDialog = (orderID) => {
  currentOrderId.value = orderID;
  reviewForm.value = {
    rating: 5,
    comment: ''
  };
  reviewDialogVisible.value = true;
};

// 提交评价
const submitReview = async () => {
  if (!currentOrderId.value) {
    ElMessage.warning('订单ID无效');
    return;
  }

  try {
    // 获取订单信息
    const orderInfo = orders.value.find(order => order.orderID === currentOrderId.value);
    if (!orderInfo) {
      ElMessage.warning('找不到订单信息');
      return;
    }

    // 构建评价参数
    const reviewParams = {
      orderID: currentOrderId.value,
      itemID: orderInfo.itemID,
      buyerID: orderInfo.buyerID,
      sellerID: orderInfo.sellerID,
      status: 'completed',
      buyerRating: reviewForm.value.rating,
      buyerReview: reviewForm.value.comment,
      createTime: new Date().toISOString(),
      addrID: orderInfo.addrID
    };

    try {
      // 调用评价API
      const response = await MarketItemApi.evaluateTransaction(reviewParams);

      // 解析响应
      // if (typeof response === 'string') {
      //   responseData = JSON.parse(response);
      // } else {
      //   responseData = response;
      // }

      ElMessage.success('评价提交成功');
      reviewDialogVisible.value = false;
      // 刷新订单列表
      await fetchOrders();

    } catch (e) {
      ElMessage.error( '评价提交失败');
    }

  } catch (error) {
    ElMessage.error(`评价提交失败: ${error.message}`);
  }
};

// 页面加载时获取订单
onMounted(() => {
  fetchOrders();
});
</script>

<template>
  <div class="order-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="全部订单" name="all"></el-tab-pane>
      <el-tab-pane label="待收货" name="inProgress"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
    </el-tabs>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="filteredOrders.length > 0" class="order-list">
      <div v-for="order in filteredOrders" :key="order.orderID" class="order-item">
        <div class="order-header">
          <span class="order-id">订单号: {{ order.orderID }}</span>
          <span class="order-time">{{ formatTime(order.creationTime) }}</span>
          <el-tag :type="getStatusType(order.status)" size="small">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>

        <div class="order-content" @click="viewOrderDetail(order.orderID)">
          <div class="order-image" :style="{ backgroundImage: `url(${order.itemImage || defaultImage})` }"></div>
          <div class="order-info">
            <div class="order-title">{{ order.itemTitle || '未知商品' }}</div>
            <div class="order-seller">卖家: {{ order.sellerName || '用户' + order.sellerID }}</div>
            <div class="order-price">¥{{ order.itemPrice || '0.00' }}</div>
          </div>
        </div>

        <div class="order-footer">
          <div v-if="order.status === 'completed'" class="review-section">
            <div v-if="order.buyerReview" class="review-content">
              <div class="review-title">我的评价:</div>
              <div class="review-text">{{ order.buyerReview }}</div>
              <div class="review-rating">
                <el-rate
                  v-model="order.buyerRating"
                  disabled
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </div>
            </div>
            <el-button
              v-else
              type="primary"
              size="small"
              @click="openReviewDialog(order.orderID)"
            >
              评价订单
            </el-button>
          </div>

          <div class="action-buttons">
            <el-button
              v-if="order.status === 'inProgress'"
              type="success"
              size="small"
              @click="confirmReceipt(order.orderID)"
            >
              确认收货
            </el-button>
            <el-button
              v-if="order.status === 'inProgress'"
              type="danger"
              size="small"
              @click="cancelOrder(order.orderID)"
            >
              取消订单
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="contactSeller(order.sellerID, order.itemID)"
            >
              联系卖家
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="viewOrderDetail(order.orderID)"
            >
              订单详情
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <el-empty v-else description="暂无订单"></el-empty>

    <!-- 评价弹窗 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="评价订单"
      width="500px"
    >
      <div class="review-dialog-content">
        <div class="rating-section">
          <span>评分:</span>
          <el-rate v-model="reviewForm.rating" />
        </div>
        <div class="comment-section">
          <span>评价内容:</span>
          <el-input
            v-model="reviewForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请分享您对商品和交易的看法..."
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.order-container {
  padding: 20px;
  background-color: #fff;
  width: calc( 100% - 20px);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .loading-container, .empty-container {
    padding: 40px 0;
    text-align: center;
  }

  .order-list {
    margin-top: 20px;

    .order-item {
      margin-bottom: 20px;
      border: 1px solid #eee;
      border-radius: 8px;
      overflow: hidden;
      transition: box-shadow 0.3s;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .order-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 16px;
        background-color: #f9f9f9;
        border-bottom: 1px solid #eee;

        .order-id {
          font-size: 14px;
          color: #666;
        }

        .order-time {
          font-size: 14px;
          color: #999;
        }
      }

      .order-content {
        display: flex;
        padding: 16px;
        cursor: pointer;

        .order-image {
          width: 100px;
          height: 100px;
          border-radius: 4px;
          background-size: cover;
          background-position: center;
          margin-right: 16px;
          flex-shrink: 0;
        }

        .order-info {
          flex: 1;

          .order-title {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin-bottom: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }

          .order-seller {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
          }

          .order-price {
            font-size: 18px;
            font-weight: 600;
            color: #ff2442;
          }
        }
      }

      .order-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-top: 1px solid #eee;

        .review-section {
          flex: 1;

          .review-content {
            .review-title {
              font-size: 14px;
              color: #666;
              margin-bottom: 4px;
            }

            .review-text {
              font-size: 14px;
              color: #333;
              margin-bottom: 4px;
            }

            .review-rating {
              margin-top: 4px;
            }
          }
        }

        .action-buttons {
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  .review-dialog-content {
    .rating-section {
      margin-bottom: 16px;
      display: flex;
      align-items: center;

      span {
        margin-right: 12px;
        font-size: 14px;
        color: #666;
      }
    }

    .comment-section {
      span {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #666;
      }
    }
  }
}
</style>
